<?php
class TelescopeController extends Controller{
        /**
         * Filters for this controller
         * 
         * @return type
         */
        public function filters()
        {
            return array( 'accessControl' ); // perform access control for CRUD operations
        }

        /**
         * Access rules that will be used by the accessControl-filter
         * 
         * @return type
         */
        public function accessRules()
        {
            return array(
                array('allow', // allow authenticated users to access all actions
                    'users'=>array('@'),
                    'actions'=>array('index','add'),
                ),
                array('deny'),
            );
        }
        
        /**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/observation/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}
        
    /**
     * This is the action for adding a telescope for current logged
     * in user.
     */
    public function actionAdd()
    {
        // Viewmodel for use in form
        $viewmodel = new Telescope;

        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='add-form')
        {
            echo CActiveForm::validate($viewmodel);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['Telescope']))
        {
            $viewmodel->attributes=$_POST['Telescope'];
            
            if(!$viewmodel->validate()){
                // ViewModel didn't pass validation, return to add-view while displaying errors
                if(Yii::app()->request->isAjaxRequest)
                {
                        echo CJSON::encode(
                                array(
                                    'status' => 'failure',
                                    'div' => $this->renderPartial(
                                            'add', array('model' => $viewmodel),
                                            true),
                                )
                        );
                        
                }
                else
                {
                        // display the form for adding an observation
                        $this->render('add',array('model'=>$viewmodel));
                }
                Yii::app()->end();
            }

            $_user_telescope_exists = false;

            // Try to look up the telescope to see if it exists already.
            $model = Telescope::model()->findByAttributes(
                            array(
                                'name'=>$viewmodel->name,
                            )
                    );

            if(!$model){
                    // Telescope doesnt exist yet, create new model
                    $model = new Telescope;

                    // Fill telecope model with values from ViewModel
                    $model->name = $viewmodel->name;
                    $model->aperture = $viewmodel->aperture;
                    $model->focallength = $viewmodel->focallength;
                    $model->magnification = $viewmodel->magnification;
                    $model->filter = $viewmodel->filter;

            }
            else 
            {

                    // Telescope already exists, check if already connected to this user
                    foreach($model->users AS $user)
                    {
                            if($user->user_ID === Yii::app()->user->id)
                            {
                                    $_user_telescope_exists = true;
                                    break;
                            }
                    }
            }
            // save() by default validates the model
            if($model->save(/*$runValidation=true*/))
            {
                    if(!$_user_telescope_exists)
                    {
                            // User-Telescope relation not yet made, add it
                            $user_telescope = new UsersTelescopes;
                            $user_telescope->user_ID = Yii::app()->user->id;
                            $user_telescope->telescope_ID = $model->telescope_ID;
                            $user_telescope->save();
                    }

                    if(Yii::app()->request->isAjaxRequest)
                    {
                            echo CJSON::encode(
                                    array(
                                        'status' => 'success',
                                        'div' => 'Telescoop toegevoegd',
                                        'telescope_ID' => $model->telescope_ID,
                                        'telescope_name' => $model->name,
                                    )
                            );
                            Yii::app()->end();
                    }       
                    else
                    {
                            // Redirect user back to originating page
                            $this->redirect(array('overview/index'));
                    }

            }

        }

        if(Yii::app()->request->isAjaxRequest)
        {
                echo CJSON::encode(
                        array(
                            'status' => 'failure',
                            'div' => $this->renderPartial(
                                    'add', array('model' => $viewmodel),
                                    true),
                        )
                );
                Yii::app()->end();
        }
        else
        {
                // display the form for adding an observation
                $this->render('add',array('model'=>$viewmodel));
        }

    }
}
